package com.okcoin.websocket.client;

import com.okcoin.dao.DataWriteDao;
import com.okcoin.dao.impl.DataWriteDaoImp;
import org.apache.log4j.Logger;

import com.okcoin.websocket.WebSocketBase;
import com.okcoin.websocket.WebSocketService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 订阅信息处理类需要实现WebSocketService接口
 *
 * @author okcoin
 */
public class BuissnesWebSocketServiceImpl implements WebSocketService {
    private Logger log = Logger.getLogger(WebSocketBase.class);
  //  private DataWriteDao dataWriteDao;

    /*
     *
     * 把返回的数据存数据库
     * @author sky
     * @date 2018/10/12 10:10
     * @param [msg]
     * @return void
     */
    @Override
    public void onReceive(String msg) {
        //log.info("WebSocket Client received message: " + msg);
        //判断是否是心跳包返回(心跳包首个字符是`{` )
        if ('{' == msg.charAt(0)) {
            //System.out.println("yes:"+msg);
        } else {
            JSONArray jsonArray = new JSONArray(msg);
            for (Object object : jsonArray) {
                JSONObject JO = (JSONObject) object;
                String addChannelString = JO.getString("channel");
                //判断是否为订阅
                if ("addChannel".equals(addChannelString)) {
                    JSONObject dataObj = JO.getJSONObject("data");
                    if (dataObj.getBoolean("result")) {
                        log.info(dataObj.getString("channel") + "订阅成功");
                    } else {
                        log.error(dataObj.getString("channel") + "订阅失败");
                    }
                } else {
                    //这里处理返回的真正数据
                    if (JO!=null&&addChannelString!=null){
                        Runner1 r = new Runner1(); //new一个线程对象Runner1
                        r.run(JO,addChannelString);//方法调用
                    }
                }
            }
        }
    }
    class Runner1 extends Thread { //本身就是一个Thread，就不用再new一个
        public void run(JSONObject JO,String addChannelString) { //run方法里写的是什么，线程调用时执行的就是什么
                DataWriteDao dataWriteDao=new DataWriteDaoImp();
               dataWriteDao.webscoketWrite(JO,addChannelString);

        }
    }
}
